<?php
ini_set('display_errors','off');
error_reporting(0);//disable PHP error reporting, to avoid JS error
define('_WITH_ADSAME', true);
header('Content-Type: application/javascript');
$pos = isset($_GET['pos']) ? $_GET['pos'] : 'top';
$aid = isset($_GET['aid']) ? $_GET['aid'] : 0;
if (!$aid) {//get aid from referer URL
    preg_match('%/(\d+)(_\d+)?\.shtml%',$_SERVER['HTTP_REFERER'],$m);
    if (isset($m[1])) $aid = $m[1];
}
if (!$pos || !$aid) die('//parameters invalid');
$vbc_base = "http://hfm.adsame.com/s?z=hfm&";
$vbc = @json_decode(file_get_contents('http://ads.hearst.com.cn/index.php?do=launch.getVBCAds&id='.$aid), 1);
if (!$vbc[$pos]) die('//no vbc ads for this position');
$src = $vbc_base.$vbc[$pos];
$randid = uniqid('hd');
if (!_WITH_ADSAME) {
    echo "document.write('<scr'+'ipt src=\"$src\"></scr'+'ipt>');";
    die();
}
?>
//write a hidden object for testing
var h<?php echo $randid;?> = ('h'+Math.random()).replace('.','');
document.write('<input type="hidden" id="'+h<?php echo $randid;?>+'" />');
//for script ads
<?php if ($_GET['type']=='js'): ?>
document._dw<?php echo $randid;?> = document.write; //backup
document.write = function (s) { //rewrite document.write
    if (s.match(/adsame/i)) { //the caller of document.write is adsame
        s = "<div style='display:none' id='_unpack_me_later_if_needed'>"+encodeURIComponent(s)+"</div>"; //stop it
        document.write = document._dw<?php echo $randid;?>; //revert document.write
        document._dw<?php echo $randid;?>('<scr'+'ipt src="<?php echo $src; ?>"></scr'+'ipt>'); //write our vbc ads code
    }
    document._dw<?php echo $randid;?>(s); //normal document.write
};
<?php elseif ($_GET['type']=='iframe'): ?>
//for iframe ads
setTimeout(function(){
    var o = document.getElementById(h<?php echo $randid;?>).nextSibling;
    var i = 8;
    while (i > 0 && o != null) {
        if ( o.nodeName == 'SCRIPT' ) break;
        if ( o.nodeName == 'IFRAME' ) {
            //if (document._dw<?php echo $randid;?>) document.write = document._dw<?php echo $randid;?>; //revert document.write
            o.rel = o.src;
            o.src = "<?php echo $src; ?>&op=1";
            break;
        }
        o = o.nextSibling;
        i --;
    }
}, 1);
<?php endif; ?>
